const express = require("express")
const multer = require("multer")
const fs = require("fs")
const path = require("path")
const moment = require("moment")
const multerObj = multer({ dest: "./../src/upluad", limits: "5mb" })
const db = require("./../libs/DBhelper")

let apiRouter = express.Router({

})


apiRouter.post("/login", function(request, response, next) {
    let parmas = [
        request.body.uname,
        request.body.upwd,

    ]

    let sql = "SELECT `uid`,`uname`,`uyz`,`utype` FROM `aolaigou` WHERE ustatus=1 AND uname=? AND upwd=?"
    db.exec(sql, parmas, (err, result) => {
            if (!err && result.length >= 1) {
                request.session["userInfo"] = Object.assign({}, result)


                response.json({
                    msg: "登录成功",
                    data: result,
                    status: 1
                })
            } else {
                response.json({
                    msg: "登录失败",
                    status: -1,
                    err
                })
            }
        })
        // response.end("login")
})

apiRouter.post("/reg", function(request, response, next) {
    let parmas = [
        request.body.uname,
        request.body.upwd,
        request.body.uyz
    ];
    let sql = "INSERT INTO `aolaigou`(`uname`,`upwd`,`uyz`) VALUES(?,?,?);"
    db.exec(sql, parmas, function(err, result) {

            if (err) {
                request.session["userInfo"] = Object.assign({}, result);

                response.json({
                    msg: "注册失败",

                    status: -3,
                    err,
                    res: result
                })
                return
            }
            if (result.affectedRows >= 1) {
                response.json({
                    msg: "注册成功",

                    status: 1
                })
            } else {
                response.json({
                    msg: "注册失败",

                    status: -1
                })
            }
        })
        // response.end()
})

apiRouter.get("/goodslist", (request, response, next) => {
    var resJson = JSON.parse(fs.readFileSync("./data/list.json").toString());
    response.json(resJson)
})

apiRouter.get("/goodsById/:pid", (request, response, next) => {
    let pid = request.params.pid
    var resArr = JSON.parse(fs.readFileSync("./data/list.json").toString())
    var resList = resArr.filter((el) => {
        return el.pid == pid
    })

    if (resList.length >= 1) {
        response.json({
            msg: "查询成功",
            status: 1,
            data: resList[0]
        })
    } else {
        response.json({
            msg: "查询失败",
            status: -1,
            data: null
        })
    }
})

apiRouter.post("/addCart", async(request, response, next) => {
        var parmasQuery = [
            request.body.uid,
            request.body.pid,
            request.body.psize,
            request.body.pname,
            request.body.pprice,
            request.body.pnum,

        ]
        var querySql = "SELECT * FROM cart WHERE u_status=1 AND u_complete=1 AND u_id=? AND p_id=? AND p_size=?"


        var res = await db.execAsync(querySql, parmasQuery)

        if (res.length >= 1) {

            let parmasUpdate = [
                request.body.pnum,
                request.body.uid,
                request.body.pid,
                request.body.psize

            ]

            var updateSql = "UPDATE cart SET p_num=p_num+?,u_total=p_num*p_price  WHERE u_status=1 AND u_complete=1 AND u_id=? AND p_id=? AND p_size=?"

            var res = await db.execAsync(updateSql, parmasUpdate)

            if (res.affectedRows >= 1) {
                response.json({
                    msg: "加入购物车成功u",
                    status: 1,

                })
            } else {
                response.json({
                    msg: "加入购物车失败u",
                    status: -1,

                })
            }

        } else {
            var paramsInsert = [
                request.body.pid,
                request.body.pphoto,
                request.body.pname,
                request.body.pprice,
                request.body.psize,
                request.body.pnum,
                request.body.uid,
                request.body.pnum * request.body.pprice,
                moment().format("YYYY-MM-DD HH:mm:ss")
            ];

            var insertSQL = "INSERT INTO `cart`(`p_id`,`p_photo`,`p_name`,`p_price`,`p_size`,`p_num`,`u_id`,`u_total`,`u_time`)VALUES(?,?,?,?,?,?,?,?,?)"
            var res = await db.execAsync(insertSQL, paramsInsert)
            if (res.affectedRows >= 1) {
                response.json({
                    msg: "加入购物车成功i",
                    status: 1,

                })
            } else {
                response.json({
                    msg: "加入购物车失败i",
                    status: -1,

                })
            }
        }
    })
    //get请求
    // 参数 uid
apiRouter.get("/carts", async(request, response, next) => {

    let parmas = [
        request.query.uid

    ]
    let query = "SELECT * FROM `cart` WHERE u_status=1 AND u_complete=1 AND u_id=?"

    var res = await db.execAsync(query, parmas)

    response.json({
        msg: res.length >= 1 ? "查询成功" : "查询失败",
        data: res
    })


})

apiRouter.post("/modify", async(request, response, next) => {
    let paramas = [
        request.body.pnum,
        request.body.cid

    ]
    let sql = "UPDATE `cart` SET p_num=? ,u_total=p_num*p_price WHERE c_id=? AND u_status=1 AND u_complete=1"
    var res = await db.execAsync(sql, paramas)
    response.json({
        msg: res.affectedRows >= 1 ? "修改成功" : "修改失败",
        status: res.affectedRows >= 1 ? 1 : -1
    })
})



apiRouter.post("/delete", async(request, response, next) => {
    let paramas = [

        request.body.cid

    ]
    let sql = "UPDATE cart SET u_status=0 WHERE c_id=? AND  u_status=1 AND u_complete=1"
    var res = await db.execAsync(sql, paramas)
    response.json({
        msg: res.affectedRows >= 1 ? "删除成功" : "删除失败",
        status: res.affectedRows >= 1 ? 1 : -1
    })
})


apiRouter.get("/quit", (request, response, next) => {
    request.session["userInfo"] = null;
    response.clearCookie("loginInfo");
    response.json({
        msg: "退出成功",
        status: 1
    });
});


module.exports = apiRouter;